<template>
  <el-checkbox-group v-model="chooseds" @change="handleChange" :disabled="disable">
    <el-checkbox v-for="(opt, id) in options" :key="id + 'checkbox'" :label="opt.label" :name="opt.label" />
  </el-checkbox-group>
</template>
<script>
function getOpitonValue(value, opt, type = "id") {
  let length = opt.length;
  if (!length) {
    return {};
  }
  while (length--) {
    let key = type === "id" ? "value" : "label";
    if (opt[length][key] == value) {
      return opt[length];
    }
  }
  return {};
}

export default {
  name: "check-box",
  props: ["value", "options", "type", "disable"],
  watch: {
    options() {
      this.$nextTick(() => {
        this.resetChooseds();
      });
    },
    chooseds() {
      // const options = this.options;
      // const type = this.type;
      // console.log(val);
      // const inputValue = val
      //   .map(label => {
      //     let option = getOpitonValue(label, options, "name");
      //     let listValue = {};
      //     if (!option.value) {
      //       return null;
      //     }
      //     listValue.id = option.value;
      //     listValue.name = option.label;
      //     listValue.type = type;
      //     return listValue;
      //   })
      //   .filter(value => value);
      // console.log(inputValue);
      // if (this.value) {
      //   this.$emit("input", inputValue);
      //   this.$emit("change", inputValue);
      // }
    },
    value(v) {
      console.log(v);
    }
  },
  data() {
    return {
      chooseds: []
    };
  },
  created() {
    this.resetChooseds();
  },
  methods: {
    resetChooseds(value) {
      const opt = this.options;
      if (!opt.length) {
        return;
      }
      this.chooseds = (value || this.value)
        .map(v => getOpitonValue(v.id, opt).label)
        .filter(v => v);
      this.$nextTick(() => {
        this.handleChange(this.chooseds);
      });
    },
    handleChange(val) {
      const options = this.options;
      const type = this.type;
      const inputValue = val
        .map(label => {
          let option = getOpitonValue(label, options, "name");
          let listValue = {};
          if (!option.value) {
            return null;
          }
          listValue.id = option.value;
          listValue.name = option.label;
          listValue.type = type;
          return listValue;
        })
        .filter(value => value);
      this.$emit("input", inputValue);
      this.$emit("change", inputValue);
    }
  }
};
</script>

